﻿using System;
using System.Collections.Generic;
using System.Globalization;
using Phoenix.Xna.Framework.Serialization.Markup.Objects;

namespace Phoenix.Xna.Framework.Serialization.Markup
{
    /// <summary>
    /// Helps manage serialized references.
    /// </summary>
    internal class ReferenceManager
    {
        private List<string> _previousReferences = new List<string>();                                              // All referenceIDs used since last clear.
        private Dictionary<object, IMarkupObject> _instanceToMarkup = new Dictionary<object, IMarkupObject>();      // A collection of IMarkupObjects for instances.      
        private Dictionary<string, ClassMarkup> _referenceToMarkup = new Dictionary<string, ClassMarkup>();         // A collection of ClassMarkups for references.

        /// <summary>
        /// Reset the reference manager.
        /// </summary>
        public void Clear()
        {
            _referenceToMarkup.Clear();
            _instanceToMarkup.Clear();
            _previousReferences.Clear();
        }

        /// <summary>
        /// Register an object to a referenceID.
        /// </summary>
        /// <param name="referenceId">The reference ID to register.</param>
        /// <param name="markupObject">The ClassMarkup object to register.</param>
        public void AddObject(string referenceId, ClassMarkup markupObject)
        {
            if (markupObject == null)
            {
                throw new ArgumentNullException("markupObject");
            }

            if (string.IsNullOrEmpty(referenceId))
            {
                throw new ArgumentNullException("referenceId");
            }

            _referenceToMarkup.Add(referenceId, markupObject);

            if (markupObject.Instance != null)
            {
                _instanceToMarkup.Add(referenceId, markupObject);
            }
        }

        /// <summary>
        /// Register a class markup so additional references to it are translated to a ReferenceMarkup.
        /// </summary>
        /// <param name="instance">The object to register.</param>
        /// <param name="markupObject">The ClassMarkup to register.</param>
        public void AddObject(object instance, ClassMarkup markupObject)
        {
            if (markupObject != null)
            {
                if (instance == null)
                {
                    throw new ArgumentNullException("instance");
                }

                _instanceToMarkup.Add(instance, markupObject);
            }
        }

        /// <summary>
        /// Get the dereference class markup for a given reference id.
        /// </summary>
        /// <param name="referenceId">The ID of the ClassMarkup to get.</param>
        /// <returns>The ClassMarkup of the specified reference ID.</returns>
        public ClassMarkup GetMarkupFromReferenceId(string referenceId)
        {
            return _referenceToMarkup[referenceId];
        }

        /// <summary>
        /// Get a reference to a pre-existing class markup (if it exists)
        /// </summary>
        /// <param name="instance">The IMarkupObject of the instance to get.</param>
        /// <returns>Ithe IMarkupObject of the specified instance.</returns>
        public IMarkupObject GetMarkupFromInstance(object instance)
        {
            if (_instanceToMarkup.ContainsKey(instance))
            {
                ClassMarkup classMarkup = _instanceToMarkup[instance] as ClassMarkup;

                if (string.IsNullOrEmpty(classMarkup.ReferenceID))
                {
                    SetReferenceID(classMarkup);
                    _referenceToMarkup.Add(classMarkup.ReferenceID, classMarkup);
                }

                return new ReferenceMarkup(classMarkup);
            }

            return null;
        }

        private void SetReferenceID(ClassMarkup markupObject)
        {
            string preferredReferenceID = markupObject.ObjectType.Name;
            string referenceID = preferredReferenceID;
            int referenceCount = 0;

            while (_previousReferences.Contains(referenceID))
            {
                referenceID = string.Format(CultureInfo.InvariantCulture, "{0}{1}", preferredReferenceID, ++referenceCount);
            }

            _previousReferences.Add(referenceID);
            markupObject.ReferenceID = referenceID;
        }
    }
}
